#!/bin/bash
#配置flannel走kube-apiserver，调用etcd
/usr/bin/cat << EOF | /opt/kubernetes/bin/kubectl apply -f -
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: flannel
rules:
  - apiGroups: ['extensions']
    resources: ['podsecuritypolicies']
    verbs: ['use']
    resourceNames: ['psp.flannel.unprivileged']
  - apiGroups:
      - ""
    resources:
      - pods
    verbs:
      - get
  - apiGroups:
      - ""
    resources:
      - nodes
    verbs:
      - list
      - watch
  - apiGroups:
      - ""
    resources:
      - nodes/status
    verbs:
      - patch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: flannel
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: flannel
subjects:
- kind: ServiceAccount
  name: flannel
  namespace: kube-system
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: flannel
  namespace: kube-system
EOF

CLUSTER_NAME="kubernetes"
KUBE_CONFIG="flanneld.kubeconfig"
KUBE_APISERVER={{ KUBE_APISERVER }}

SECRET=$(/opt/kubernetes/bin/kubectl -n kube-system get ServiceAccount/flannel \
    --output=jsonpath='{.secrets[0].name}')

JWT_TOKEN=$(/opt/kubernetes/bin/kubectl -n kube-system get secret/$SECRET \
    --output=jsonpath='{.data.token}' | base64 -d)

/opt/kubernetes/bin/kubectl config set-cluster ${CLUSTER_NAME} \
  --certificate-authority=/opt/kubernetes/ssl/ca.pem \
  --embed-certs=true \
  --server=${KUBE_APISERVER} \
  --kubeconfig=/opt/kubernetes/cfg/${KUBE_CONFIG}

/opt/kubernetes/bin/kubectl config set-context ${CLUSTER_NAME} \
  --cluster=${CLUSTER_NAME} \
  --user=${CLUSTER_NAME} \
  --kubeconfig=/opt/kubernetes/cfg/${KUBE_CONFIG}

/opt/kubernetes/bin/kubectl config set-credentials ${CLUSTER_NAME} --token=${JWT_TOKEN} --kubeconfig=/opt/kubernetes/cfg/${KUBE_CONFIG}

/opt/kubernetes/bin/kubectl config use-context ${CLUSTER_NAME} --kubeconfig=/opt/kubernetes/cfg/${KUBE_CONFIG}

/opt/kubernetes/bin/kubectl config view --kubeconfig=/opt/kubernetes/cfg/${KUBE_CONFIG}
